<template>
  <el-dialog v-model="dialogVisible" :title="title" :before-close="onCloseDialog">
    <el-transfer
      v-model="lotNameList"
      :titles="['可选场库', '已选场库']"
      :data="lotNameAllList"
      :props="{
        label: 'name',
        key: 'id',
      }"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCloseDialog">取消</el-button>
        <el-button type="primary" @click="onSubmitDialog"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref } from "vue";
import { getCparkChargeRuleLotList, postCparkChargeRuleLotBind } from "../request";
import { ElMessage } from "element-plus";

const dialogVisible = ref(false);
const title = ref("");
const lotNameList = ref([]);
const lotNameAllList = ref([]);
const emits = defineEmits(["update"]);
const bindId = ref("");

const getLotNameList = async (id, lotNameList) => {
  lotNameAllList.value = [];
  try {
    const { data } = await getCparkChargeRuleLotList(id);
    lotNameAllList.value = data.result;
  } catch (error) {
    console.log("error", error);
  }
};
const init = async (record) => {
  await getLotNameList(record.id);
  lotNameList.value = record.lotNameList.map((key) => {
    const result = lotNameAllList.value.find((el) => {
      return key === el.name;
    });
    return result.id;
  });
  title.value = `配置【${record.name}】关联场库`;
  bindId.value = record.id;
  dialogVisible.value = true;
};
const onCloseDialog = () => {
  dialogVisible.value = false;
  lotNameList.value = [];
  lotNameAllList.value = [];
  title.value = "";
  bindId.value = "";
};
const onSubmitDialog = async () => {
  const params = lotNameList.value.map((el) => {
    const result = lotNameAllList.value.find((data) => {
      return data.id === el;
    });
    delete result.bindState;
    return result;
  });
  try {
    const { data } = await postCparkChargeRuleLotBind(bindId.value, params);
    if (data.code === 0) {
      ElMessage.success(data.result);
    }
    onCloseDialog();
  } catch (error) {
    console.log("绑定车场报错：", error);
  }
  emits("update");
};

defineExpose({ init });
</script>
